local mp = require ('MessagePack')

local upserver = ngx.shared.upserver
local cjson = require("cjson")
local random = require('math').random
local randomseed = require('math').randomseed

local function _log(str) ngx.log(ngx.ERR, str) end

local getServerByType = function (typeName, servers)
  if 'table' ~= type(servers)  then
    return nil
  end

  if typeName == nil then
    return nil
  end

  local list = servers[typeName]
  if not list then
    return nil
  end

  local len = table.getn(list)
  randomseed(os.time())
  local targetServer = list[random(len)]
  return targetServer

end

local servers = upserver:get('servers')
if not servers then
  return ngx.say("servers not ready")
end
servers = mp.unpack(servers)
local str_servers = cjson.encode(servers)

local typeName, newUri = string.match(ngx.var.request_uri, '/(.-)/(.*)')
newUri = '/' .. newUri

local oMethod = ngx.req.get_method()
local proxyMethod
if oMethod=="GET" then proxyMethod = ngx.HTTP_GET
elseif oMethod=="POST" then proxyMethod = ngx.HTTP_POST
elseif oMethod=="PUT" then proxyMethod = ngx.HTTP_PUT
elseif oMethod=="DELETE" then proxyMethod = ngx.HTTP_DELETE
elseif oMethod=="OPTION" then proxyMethod = ngx.HTTP_OPTION
end
if not proxyMethod then _log("unsupport method" .. oMethod) return end

local oheader = ngx.req.get_headers()

local targetServer = getServerByType(typeName, servers)

if nil == targetServer then
  ngx.say("nil upstream server")
  return
end


local upUrl='/proxy/' .. targetServer .. newUri
ngx.req.read_body()
local resp = ngx.location.capture(upUrl,{
  method = proxyMethod,
  headers = oheader,
  body = body
})


if not resp then
    ngx.say("response error" ,err)
    return
end

ngx.status = resp.status
for k,v in pairs(resp.header) do
    if k ~= "Transfer-Encoding" and k ~= "Connection" then
        ngx.header[k] = v
    end
end
ngx.say(resp.body)
